<?php

namespace Buu\Modules\Domain\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\model\DomainConfig\DomainName;
use Doraemon\model\DomainConfig\TemplateHost;
use Encore\Admin\Widgets\Table;




class TemplateHostController extends Controller
{


    public function __construct(Request $request)
    {
        parent::__construct();

    }

    public function index(Request $request, Content $content)
    {
        $requestParams = $request->all();
        $condition = [];

        $pageSize = $request->input("per_page", 10);
        $page = $request->input("page", 1);
        $condition['AND'] = [
            'template_status' => TemplateHost::STATUS_NORMAL
        ];
        $total = TemplateHost::selectCount($condition);
        $condition['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $list = TemplateHost::selectByWhere($condition);
        if($list && is_array($list))
        {
            foreach($list as &$val){
                   $val['template'] = '模版内容';
                   $domain_list =  DomainName::selectByWhere([
                       'template_id' => $val['id'],
                       'domain_status' => [DomainName::STATUS_NORMAL , DomainName::STATUS_ONLINE]
                   ]);
                   $val['domain_list'] = $domain_list;
            }
        }
        $gridModel = new pGridDataModel($list, $total, [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableFilter();
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->column("template_name", '模版名称')->width(200);
                $grid->column("template", '模版内容')->modal('host列表', function ($model) {
                    $result = [];
                    $contentArr = json_decode($model['content'] , true);
                    foreach ($contentArr as $key =>$val){
                        $result[]=[
                            'api' => $key,
                            'host' => $val
                        ];
                    }
                    return new Table(['Api项目', 'host'], $result);
                })->width(200);
               $grid->column('domain_list', '使用域名配置')->display(function() {
                    $options='';
                    if ($this->domain_list) {
                        foreach ($this->domain_list as $value) {
                            $editUrl ='/admin/domain/edit/'.$value['id'];
                            $options = $options . '<button style="display:inline-block;margin:2px;" class="marktag btn btn-sm" data-had=""><a href="'.$editUrl.'">'.$value['domain_name'].'</a></button>';
                        }
                    }
                    return $options;
                })->style("width:300px");
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                    $actions->append('<a href="/admin/domain/template/edit/' . $actions->row->id . '" class="fa fa-edit">编辑</a>');
                    //复制功能
                    $copyUrl =  '/admin/domain/template/copy/'.$actions->row->id;
                    $actions->append('<a class="fa fa-copy" href="' . $copyUrl . '">复制</a>');
                });
            });
        $tab = new Tab();
        $tab->add('模版列表', $gridList->render());
        $tab->addLink('域名列表', '/admin/domain/index');

        $content->row($tab);
        return $content
            ->header('模版列表')
            ->breadcrumb(['text' => '模版列表']);

    }


    /*创建栏目
     *
     * */
    public function create(Request $request, Content $content, $id = 0)
    {
        $header = '添加模版';
        if ($id) {
            $header = '编辑模版';
        }
        $info  = $id ? TemplateHost::getByWhere(['id' => $id] ) :[];
        if($info && is_array($info)){
            $info['content'] = json_decode($info['content'] , true);
        }else{
            $info['content'] = array_combine(TemplateHost::KEY_MAP,['' ,'' , '' ,'' ,'','','','','','']);
        }
        $form = new Form($info);
        $form->hidden('id');
        $form->text('template_name', '模版名称')->required();
        $form->keyValue('content','模版内容')->required();
        $form->action(url('admin/domain/template/save'));
        $content->row($form);
        return $content->header($header)->breadcrumb(
            ['text' => '模版列表', 'url' => url('admin/domain/template/index')],
            ['text' => $header]);
    }


    /*创建栏目
     *
     * */
    public function copy(Request $request, Content $content, $id = 0)
    {

        $info  =  TemplateHost::getByWhere(['id' => $id] );
        $header = "复制".$info['template_name'];
        if($info && is_array($info)){
            $info['content'] = json_decode($info['content'] , true);
            $info['template_name'] =$info['template_name']."_copy";
        }

        $form = new Form($info);
        $form->text('template_name', '模版名称')->required();
        $form->keyValue('content','模版内容')->required();
        $form->action(url('admin/domain/template/save'));
        $content->row($form);
        return $content->header($header)->breadcrumb(
            ['text' => '模版列表', 'url' => url('admin/domain/template/index')],
            ['text' => $header]);
    }


    /*添加成功
     *
     * */
    public function save(Request $request)
    {
        try {
            $params = $request->all();
            $id = isset($params['id']) ? $params['id'] : 0;
            if (empty($params['content'])) {
                throw new \Exception('模版内容不能为空');
            }
            $content_arr =  array_combine($params['content']['keys'] ,$params['content']['values'] );
            if( empty($content_arr)){
                throw new \Exception('模版内容输入不为json');
            }
            $templateInfo= $id ? TemplateHost::getByWhere(['id' => $id]) : [];
            $data = [
                'content' => json_encode($content_arr),
                'template_name' => $params['template_name'],
                'template_status'  => 1,
                'admin_id' => Admin::user()->id,
            ];
            if($id){
                $result = TemplateHost::updateData($data , ['id' => $id]);
            }else{
                $result =  TemplateHost::insertData($data);
            }
            if ($result) {
                $url = url('/admin/domain/template/index');
                return redirect($url)->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '操作失败'
                ]);
                return back()->withInput()->with(compact('error'));
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '操作失败,信息:' . $e->getMessage()
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }


    /**
     * 删除
     * @param $id
     * @return void
     */
    public function del(Request $request, $id)
    {
        $list = DomainName::selectByWhere(['template_id' => $id ,'domain_status' =>DomainName::STATUS_NORMAL]);
        if($list && is_array($list)){
            return response()->json([
                'status' => false,
                'message' => "无法删除 ，请先将使用此模版的内容删除",
            ]);
        }

        TemplateHost::updateData(['template_status' => TemplateHost::STATUS_DELETE] , ['id' => $id]);
        return response()->json([
            'status' => true,
            'message' => "操作成功",
        ]);
    }






}